
const { Op } = require("sequelize");

const Employee = require('../model/employee.model')
const EmpRole = require('../model/empRole.model')
const Role = require('../model/role.model')
const { queryUtil } = require('../utils/query.util')

class EmployeeService {
    async findEmpByPhoneAndPwd(phone, password) {
        const whereOpt = { phone, password }
        let res = await Employee.findOne({
            where: whereOpt,
        })
        if (!res) {
            return
        }
        res.dataValues.roleId = await EmpRole.max('roleId', {
            where: { empId: res.dataValues.id }
        })

        return res ? res.dataValues : null
    }

    async updateById(emp) {
        const whereOpt = { id: emp.id }
        const { id, ...newEmp } = emp
        console.log(newEmp);
        const res = await Employee.update(newEmp, { where: whereOpt })
        return res[0] > 0 ? true : false
    }
    async createEmp(emp) {
        const res = await Employee.create(emp)

        await EmpRole.create({ empId: res.dataValues.id, roleId: 1 })
        return res ? res.dataValues : null
    }

    async queryAll(pageNum, pageSize, whereOpt) {
        const { onDuty, empName } = whereOpt
        const where = {}
        if (onDuty) {
            where['onDuty'] = onDuty
        }
        if (empName) {
            where['empName'] = {
                [Op.like]: '%' + empName + '%'
            }
        }

        const res = await queryUtil(pageNum, pageSize, where, Employee)
        return res
    }
}


module.exports = new EmployeeService()